package com.dong.mjblog.provider;

import com.alibaba.fastjson.JSON;
import com.dong.mjblog.dto.AccessTokenDTO;
import com.dong.mjblog.dto.UserDTO;
import com.dong.mjblog.util.HttpUtil;
import okhttp3.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author:dxf
 * @Date:2020/10/3-10-03 22:48
 */
@Component
@Mapper
public class GithubProvider {

    @Value("${github.oauth.url}")
    private String oauthUrl;

    @Value("${github.oauth.user}")
    private String oauthUser;


    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
//        String url = "https://github.com/login/oauth/access_token";
        String json = JSON.toJSONString(accessTokenDTO);
        Response response = HttpUtil.post(oauthUrl, json);
        try {
            String string = response.body().string();
//            System.out.println(string);
            String token = string.split("&")[0].split("=")[1];
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
//        MediaType mediaType
//                = MediaType.get("application/json; charset=utf-8");
//
//        OkHttpClient client = new OkHttpClient();
//      RequestBody body =  RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
////        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO),mediaType);
//        Request request = new Request.Builder()
//                .url("https://github.com/login/oauth/access_token")
//                .post(body)
//                .build();
//        try (Response response = client.newCall(request).execute()) {
//            String string = response.body().string();
//            System.out.println(string);
//            return string;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return null;
    }

    public UserDTO getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .header("Authorization","token "+accessToken)
//                    .url("https://api.github.com/user?access_token="+accessToken)
                    .url(oauthUser)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String jsonString =  response.body().string();
//                System.out.println(jsonString);
                UserDTO userDTO = JSON.parseObject(jsonString, UserDTO.class);
                return userDTO;
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }
}
